﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Datorgrafik_lab1.Helpers;

namespace Datorgrafik_lab1.Models {
    class Quad {
        private VertexPositionColor[] vertices;
        private short[] indices;

        private VertexBuffer vertexBuffer;
        private IndexBuffer indexBuffer;

        GraphicsDevice graphicsDevice;
        Vector3 Position;
        Color color;
        float Size = 1f;

        public Quad(GraphicsDevice graphicsDevice, Color color, Vector3 position, float size) {
            this.graphicsDevice = graphicsDevice;
            this.color = color;
            this.Position = position;
            this.Size = size;

            QuadVerticePositions qvp = new QuadVerticePositions(this.Position, this.Size);            

            InitializeQuadVertices(color, qvp);

            setupQuad();
        }

        private void setupQuad() {
            InitializeQuadIndices();

            vertexBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionColor), vertices.Length, BufferUsage.WriteOnly);
            indexBuffer = new IndexBuffer(graphicsDevice, typeof(short), indices.Length, BufferUsage.WriteOnly);

            vertexBuffer.SetData<VertexPositionColor>(vertices);
            indexBuffer.SetData<short>(indices);
        }

        public void Draw() {
            graphicsDevice.SetVertexBuffer(vertexBuffer);
            graphicsDevice.Indices = indexBuffer;

            graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, indices.Length / 3);
        }

        private void InitializeQuadVertices(Color color, QuadVerticePositions vp) {
            vertices = new VertexPositionColor[4];

            // top left
            vertices[0] = new VertexPositionColor(vp.topLeft, color);
            // bottom right
            vertices[1] = new VertexPositionColor(vp.bottomRight, color);
            // bottom left
            vertices[2] = new VertexPositionColor(vp.bottomLeft, color);
            // top right
            vertices[3] = new VertexPositionColor(vp.topRight, color);

        }

        private void InitializeQuadIndices() {
            //6 vertices make up 2 triangles which make up our rectangle
            indices = new short[6];

            //Front triangle 1 (bottom portion) |\
            indices[0] = 0; //top left;
            indices[1] = 1; // bottom right;
            indices[2] = 2; // bottom left;

            //Front Triangle 2 (top portion) \|
            indices[3] = 0; // top left;
            indices[4] = 3; // top right;
            indices[5] = 1; // bottom right;
        }

    }
}
